#ifndef PATHSMOOTHINGCA_H
#define PATHSMOOTHINGCA_H

#include <vector>
#include <cstdio>
#include <QDebug>
#include "ca-pathfinding/CAs/ca.h"
#include "ca-pathfinding/rules/PathSmothing.h"
#include "ca-pathfinding/neighbourhoods/moore_1.h"

class PathSmoothingCA:public CA
{

public:

    PathSmoothingCA():CA()
    {
        step=0;
    }
    ~PathSmoothingCA()
    {
        // delete current_states;
        // delete new_states;
    }


    bool next()
    {
        bool changed=false;
        for(int i=0;i<current_states->height();++i)
            for(int j=0;j<current_states->width();++j)
            {
                new_states->tiles[i][j]->state=current_states->tiles[i][j]->state;
                std::vector<Tile*> nbs=mn::neighbours(current_states,i,j);

                for(int r=0;r<psr::RULES_SIZE;++r)
                {
                    bool f=true;
                    if(current_states->tiles[i][j]->state!=EMPTY)break;
                    for(int n=0;n<psr::NEIGHBOURS_SIZE;++n)
                    {

                        if(psr::rules[r][n+1]!=ANY && nbs[n]->state!=psr::rules[r][n+1])
                        {
                            f=false;
                            break;
                        }
                    }
                    if(f)
                    {

                        State new_state=psr::rules[r][psr::NEIGHBOURS_SIZE+1];
                        changed=(new_states->tiles[i][j]->state!=new_state);
                        if(changed)new_states->tiles[i][j]->state=new_state;
                        break;

                    }
                    if(changed)break;
                }
                if(changed)break;
            }

        Grid* tmp=new_states;
        new_states=current_states;
        current_states=tmp;
        ++step;
        return changed;

    }

    void start(){
        while(next());
    }

    void start(int steps)
    {
        for(int i=0;i<steps;++i)next();
    }

    int getStep()const
    {
        return step;
    }




};




#endif // PATHSMOOTHINGCA_H
